<?php

namespace app\admin\controller\health\order;

use app\common\controller\Backend;
use app\health\model\HealthOrder;
use Exception;
use think\Db;
use think\Request;

class Order extends Backend
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new HealthOrder;
    }
    /**
     * 订单列表
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->buildSearchOrder()
                ->where($where)
                ->count();
            $totalMoney = $this->buildSearchOrder()
                ->where($where)
                ->order($sort, $order)
                ->sum("total_price");
            $list = $this->buildSearchOrder()
                ->where($where)
                ->with(['orderGoods'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list, 'totalMoney' => $totalMoney);
            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }


    /**
     * 构建查询条件
     * @Author 张旭鹏
     * @DateTime 2023-06-25
     */
    private function buildSearchOrder()
    {
        return $this->model;
    }

    /**
     * 订单发货
     * @Author 张旭鹏
     * @DateTime 2023-06-26
     */
    public function deliver()
    {
        $params = $this->request->post();
        Db::startTrans();
        $order  = $this->model->where('id', $params['order_id'] ?? 0)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        if (empty($params['logistics_name']) || empty($params['express_number'])) {
            $this->error('请输入物流公司或物流单号');
        }
        if ($order['status'] != 2) {
            $this->error('订单非待发货状态');
        }
        try {
            $order->status = 3;
            $order->deliver_time = time();
            $order->logistics_name = $params['logistics_name'];
            $order->express_number = $params['express_number'];
            $order->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('发货成功');
    }
}
